package com.three.db.config;

import com.google.common.collect.Sets;
import com.three.constant.Separator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;

/**
 * Created by ziqingwang on 2017/6/19 0019.
 */
@Configuration
public class DataSourceExistCondition extends SpringBootCondition{
//    private static Environment environment;
    private static String DATASOURCE_ORDINARY = "chess.db.ordinary";
    private static String DATASOURCE_SHARDING = "chess.db.sharding";
//    private Set<String> DATASOURCE_ORDINARY_SET= Sets.newHashSet();
//    private Set<String> DATASOURCE_SHARDING_SET= Sets.newHashSet();
    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
        boolean matched=false;
        Object propertiesName = metadata.getAnnotationAttributes(DataSourceConditional.class.getName()).get("db_name");
        if(Objects.nonNull(propertiesName)){
            String[] propertiesNameArray=(String[])propertiesName;
            matched= Arrays.stream(propertiesNameArray).allMatch(db_name->{
                String ordinaryDbStr=context.getEnvironment().getProperty(DATASOURCE_ORDINARY);
                String shardingDbStr=context.getEnvironment().getProperty(DATASOURCE_SHARDING);
                return (StringUtils.isNotEmpty(ordinaryDbStr)&&ordinaryDbStr.contains(db_name))||
                        (StringUtils.isNotEmpty(shardingDbStr)&&shardingDbStr.contains(db_name));
            });
        }
        return new ConditionOutcome(matched,"数据库"+propertiesName.toString()+"——"+matched);
    }

//    @Override
//    public void setEnvironment(Environment environment) {
//        this.environment=environment;
//        DATASOURCE_ORDINARY_SET=Sets.newHashSet(environment.getProperty(DATASOURCE_ORDINARY).split(Separator.COMMA));
//        DATASOURCE_SHARDING_SET=Sets.newHashSet(environment.getProperty(DATASOURCE_SHARDING).split(Separator.COMMA));
//    }

//    /**
//     * 对比判断配置是否启动该db
//     * @param dbName
//     * @return
//     */
//    private boolean hadDb(String dbName){
//        return DATASOURCE_ORDINARY_SET.contains(dbName)||DATASOURCE_SHARDING_SET.contains(dbName);
//    }
}
